package com.hemaapp.yjnh.activity;

import java.util.ArrayList;

import xtom.frame.util.XtomToastUtil;
import xtom.frame.view.XtomListView;
import xtom.frame.view.XtomRefreshLoadmoreLayout;
import xtom.frame.view.XtomRefreshLoadmoreLayout.OnStartListener;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.hemaapp.hm_FrameWork.HemaNetTask;
import com.hemaapp.hm_FrameWork.dialog.HemaButtonDialog;
import com.hemaapp.hm_FrameWork.result.HemaArrayResult;
import com.hemaapp.hm_FrameWork.result.HemaBaseResult;
import com.hemaapp.hm_FrameWork.result.HemaPageArrayResult;
import com.hemaapp.hm_FrameWork.view.RefreshLoadmoreLayout;
import com.hemaapp.yjnh.BaseFragmentActivity;
import com.hemaapp.yjnh.BaseHttpInformation;
import com.hemaapp.yjnh.BaseUtil;
import com.hemaapp.yjnh.R;
import com.hemaapp.yjnh.adapter.CmnBookProductionAdapter;
import com.hemaapp.yjnh.bean.ImgItemsBean;
import com.hemaapp.yjnh.listener.OnItemClickListener;
import com.hemaapp.yjnh.bean.Blog;
import com.hemaapp.yjnh.bean.ClientDetails;
import com.hemaapp.yjnh.bean.Img;
import com.hemaapp.yjnh.bean.User;
import com.hemaapp.yjnh.utils.ImageUtils;
import com.hemaapp.yjnh.view.ShowTextPop;

/**普通预约类商家详情
 * @author GuiyouZhang
 * 创建时间：2015年9月16日
 */
public class CmnBookMerchantDetailActivity extends BaseFragmentActivity implements OnClickListener{

	private TextView titleText;
	private ImageButton titleLeft;
	private Button titleRight;
	private ImageView titleLove;

	private RefreshLoadmoreLayout parentLayout;
	private ScrollView scrollview;
	private ImageView image;
	private TextView tv_merchant_name;//商家名称
	private RatingBar ratingBar;
	private TextView tvPhone;
	private TextView tvConsultOnline;
	private TextView tvMerchantAddress;
	private LinearLayout llAttation;
	private TextView tvAttation;
	private RelativeLayout layoutProducts;
	private RelativeLayout layoutIntroduce;
	private View lineProducts;
	private View lineIntroduce;

	private LinearLayout ll_return_top;
	private LinearLayout layout_info;
	private TextView tv_info;
	private ImageView iv_info;
	private XtomListView listview;

	private String client_id;//当前商家的id
	private User user;
	private ClientDetails details;
	private ArrayList<Blog> zouzous = new ArrayList<Blog>();//商家的走走商品
	private CmnBookProductionAdapter adapter;
	private int curPage = 0;
    private String keytype = "9";//9:乐乐商品   10:走走相关
    private String keyid = "无";//当keytype=9时，keyid=地名，如"济阳"，无需时传"无"
    //keytype=10时，keyid=7对应露营地所有商品;71房车露营商品;72自驾车露营商品;73帐篷露营商品;74商品区商品;75房车商品;76景区商品

	@Override
	public void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.activity_merchant_detail);
		user = getApplicationContext().getUser();
		super.onCreate(savedInstanceState);
        String token = user == null?"":user.getToken();
        getNetWorker().clientGet(token, client_id);
	}

	@Override
	protected void getExras() {
		client_id = mIntent.getStringExtra("client_id");
	}

	@Override
	protected void findView() {
		titleText = (TextView) findViewById(R.id.title_text);
		titleLeft = (ImageButton) findViewById(R.id.title_left_btn);
		titleRight = (Button) findViewById(R.id.title_right_btn);
		titleLove = (ImageView) findViewById(R.id.title_right_img);

		parentLayout = (RefreshLoadmoreLayout) findViewById(R.id.layout_refresh);
		scrollview = (ScrollView) findViewById(R.id.scrollview);
		image = (ImageView) findViewById(R.id.img_merchant);
		tv_merchant_name = (TextView) findViewById(R.id.tv_merchant_name);
		ratingBar = (RatingBar) findViewById(R.id.ratingBar);
		tvMerchantAddress = (TextView)findViewById( R.id.tv_merchant_address );
		tvPhone = (TextView)findViewById( R.id.tv_phone );
		tvConsultOnline = (TextView)findViewById( R.id.tv_consult_online );
		llAttation = (LinearLayout)findViewById( R.id.ll_attation );
		tvAttation = (TextView)findViewById( R.id.tv_attation );
		layoutProducts = (RelativeLayout) findViewById( R.id.layout_all_production );
		layoutIntroduce = (RelativeLayout) findViewById( R.id.layout_introduce );
		lineProducts = findViewById(R.id.line_products);
		lineIntroduce = findViewById(R.id.line_introduce);
		ll_return_top = (LinearLayout) findViewById(R.id.ll_return_top);//回到顶部
		layout_info = (LinearLayout) findViewById(R.id.layout_info);
		tv_info = (TextView) findViewById(R.id.tv_info);
		iv_info = (ImageView) findViewById(R.id.iv_info);
		listview = (XtomListView) findViewById(R.id.listview);
		listview.setFocusable(false);
	}

	@Override
	protected void setListener() {
		titleText.setText("商家详情");
		titleLeft.setOnClickListener(this);
		titleRight.setVisibility(View.GONE);
		titleLove.setVisibility(View.VISIBLE);
		titleLove.setImageResource(R.drawable.star_while_stroke);
		titleLove.setOnClickListener(this);
		tvMerchantAddress.setOnClickListener(this);
		ll_return_top.setOnClickListener(this);
		image.setOnClickListener(this);
		tvPhone.setOnClickListener(this);
		tvConsultOnline.setOnClickListener(this);
		parentLayout.setOnStartListener(new StartListener());
		layoutProducts.setOnClickListener(this);
		layoutIntroduce.setOnClickListener(this);
		iv_info.setOnClickListener(this);
		listview.setFocusable(false);
	}

	private class StartListener implements OnStartListener {

		@Override
		public void onStartRefresh(XtomRefreshLoadmoreLayout v) {
			curPage = 0;
			String token = "";
			if (user != null) {
				token = user.getToken();
			}
			getNetWorker().clientGet(token, client_id);
			getBlogList();
		}

		@Override
		public void onStartLoadmore(XtomRefreshLoadmoreLayout v) {
			curPage++;
			getBlogList();
		}
	}

	@Override
	protected void callBeforeDataBack(HemaNetTask netTask) {
		BaseHttpInformation information = (BaseHttpInformation) netTask
				.getHttpInformation();
		switch (information) {
			case CLIENT_GET:
			case BLOG_LIST:
				showProgressDialog("请稍候");
				break;
		}
	}

	@Override
	protected void callAfterDataBack(HemaNetTask netTask) {
		BaseHttpInformation information = (BaseHttpInformation) netTask
				.getHttpInformation();
		switch (information) {
			case CLIENT_GET:
			case BLOG_LIST:
				cancelProgressDialog();
				break;
		}
	}

	@Override
	protected void callBackForServerSuccess(HemaNetTask netTask,
											HemaBaseResult baseResult) {
		BaseHttpInformation information = (BaseHttpInformation) netTask
				.getHttpInformation();
		switch (information) {
			case CLIENT_GET:
				HemaArrayResult<ClientDetails> uResult = (HemaArrayResult<ClientDetails>) baseResult;
				details = uResult.getObjects().get(0);
				setData();
                //0普通用户;1田家用户;2地标商家;3村游商家;4省级代理;5运营商;6乐乐商家;7特产商家;8粮库商家;
                // 11走走露营商家;12走走房车商家;13走走景区商家;21苗木;22花卉;23家电;24日用商品
                String role = details.getRole();
                if (role.equals("3")) {
                    keytype = "5";
                    keyid = "无";
                }else if (role.equals("6")) {
                    keytype = "9";
                    keyid = "无";
                }else if (role.equals("12")) {
                    keytype = "10";
                    keyid = "75";
                }else if (role.equals("13")) {
                    keytype = "10";
                    keyid = "76";
                }
                getBlogList();
				break;
			case BLOG_LIST:
				String page = netTask.getParams().get("page");
				HemaPageArrayResult<Blog> bResult = (HemaPageArrayResult<Blog>) baseResult;
				if (bResult == null || bResult.getObjects() == null)
					return;
				ArrayList<Blog> blogs = bResult.getObjects();
				if ("0".equals(page)) {// 刷新
					parentLayout.refreshSuccess();
					zouzous.clear();
					zouzous.addAll(blogs);
				}else {
					parentLayout.loadmoreSuccess();
					if (blogs.size() > 0)
						this.zouzous.addAll(blogs);
					else {
						parentLayout.setLoadmoreable(false);
						XtomToastUtil.showShortToast(mContext, "已经到最后啦");
					}
				}
				refreshData(-1);
				break;
			case FOLLOW_COLLECT_SAVEOPERATE:
				String oper = netTask.getParams().get("oper");
				ShowTextPop stp = new ShowTextPop(mContext,
						findViewById(R.id.father));
				// 操作	1添加 ，2取消 ;3：清空
				if (oper.equals("1")) {
					titleLove.setImageResource(R.drawable.heart_while);
					details.setFollowflag("1");
					stp.setText("已关注");
					stp.setDrawable(R.drawable.follow, 0, 0, 0);
				}else {
					titleLove.setImageResource(R.drawable.heart_while_stroke);
					details.setFollowflag("0");
					stp.setText("取消关注");
					stp.setDrawable(R.drawable.unfollow, 0, 0, 0);
				}
				stp.show();
				break;
		}
	}

	@Override
	protected void callBackForServerFailed(HemaNetTask netTask,
										   HemaBaseResult baseResult) {
		BaseHttpInformation information = (BaseHttpInformation) netTask
				.getHttpInformation();
		switch (information) {
			case CLIENT_GET:
				showTextDialog("获取商家信息失败！");
				titleText.postDelayed(new Runnable() {

					@Override
					public void run() {
						finish();
					}
				}, 1000);
				break;
			case BLOG_LIST:
				showTextDialog(baseResult.getMsg());
				break;
			case FOLLOW_COLLECT_SAVEOPERATE:
				String oper = netTask.getParams().get("oper");
				// 操作	1添加 ，2取消 ;3：清空
				if (oper.equals("1")) {
					showTextDialog("添加关注失败!");
				}else {
					showTextDialog("取消关注失败!");
				}
				break;
			default:
				break;
		}
	}

	@Override
	protected void callBackForGetDataFailed(HemaNetTask netTask, int failedType) {
		BaseHttpInformation information = (BaseHttpInformation) netTask
				.getHttpInformation();
		switch (information) {
			case CLIENT_GET:
				showTextDialog("获取商家信息失败！");
				titleText.postDelayed(new Runnable() {

					@Override
					public void run() {
						finish();
					}
				}, 1000);
				break;
			case BLOG_LIST:
				refreshData(failedType);
				break;
			case FOLLOW_COLLECT_SAVEOPERATE:
				String oper = netTask.getParams().get("oper");
				// 操作	1添加 ，2取消 ;3：清空
				if (oper.equals("1")) {
					showTextDialog("添加关注失败!");
				}else {
					showTextDialog("取消关注失败!");
				}
				break;
			default:
				break;
		}
	}

	private void refreshData(int failedType) {
		if (null == adapter) {
			adapter = new CmnBookProductionAdapter(mContext, zouzous);
			adapter.setEmptyString("暂时没有商品");
			adapter.setClickListener(new OnItemClickListener() {
				@Override
				public void onClickListener(int position) {
					Intent it = BaseUtil.createBlogIntent(mContext, zouzous.get(position).getType());
                    it.putExtra("blog_id", zouzous.get(position).getId());
                    startActivity(it);
				}
			});
			listview.setAdapter(adapter);
			BaseUtil.setListViewHeightBasedOnChildren(listview, 50, this);
		}else {
			BaseUtil.setListViewHeightBasedOnChildren(listview, 50, this);
			adapter.setEmptyString("暂时没有商品");
			adapter.notifyDataSetChanged();
		}
		adapter.setFailtype(failedType);
	}

	/**获取村游商品
	 *
	 */
	private void getBlogList() {
		getNetWorker().blogList(keytype, keyid, "1", "1", "", "", "", "", "", client_id, "", "", "", "", curPage+"");
	}

	private void setData() {
		if (details == null) {
			return;
		}
		tv_merchant_name.setText(details.getNickname());
		ImageUtils.loadBigImage(mContext, details.getBackimg(), image);
		Float score = Float.parseFloat(details.getStarscore());
		ratingBar.setRating(score);
		tvMerchantAddress.setText(details.getAddress());
		if (!isNull(details.getBuycontent())) {
			tvAttation.setText(details.getBuycontent());
		}else
			tvAttation.setText("暂无内容");
		//判断关注标记	0未关注；1已关注
		String follow = details.getFollowflag();
		if (follow==null || follow.equals("0")) {
			titleLove.setImageResource(R.drawable.heart_while_stroke);
		}else {
			titleLove.setImageResource(R.drawable.heart_while);
		}
		//价值图文详情
		tv_info.setText(details.getContent());
        ImageUtils.loadBigImage(mContext, details.getImgbigurl0(), iv_info);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.title_left_btn:
				finish();
				break;
			case R.id.title_right_img:
				if (BaseUtil.isLogin()) {
					String token = getApplicationContext().getUser().getToken();
					if ("0".equals(details.getFollowflag())) {//未关注
						getNetWorker().FolColOperate(token, "1", "1", details.getId());
					}else {//已关注
						getNetWorker().FolColOperate(token, "1",  "2", details.getId());
					}
				} else {
					Intent itCart = new Intent(mContext, LoginActivity.class);
					startActivity(itCart);
				}
				break;
			case R.id.img_merchant:
				if (details == null)
					break;
				Intent itLarge = new Intent(mContext, ShowLargeImageActivity.class);
				String imgurl_detail = details.getBackimg();
				ArrayList<Img> imgs = new ArrayList<Img>();
				Img img = new Img(imgurl_detail);
				imgs.add(img);
				itLarge.putExtra("imgs", imgs);//所有的图片地址
				itLarge.putExtra("position", 1);//当前是第几张图片
				startActivity(itLarge);
				break;
			case R.id.ll_return_top:
				scrollview.smoothScrollTo(0, 0);
				break;
			case R.id.tv_merchant_address:
				Intent itAddress = new Intent(mContext, SellerMapActivity.class);
				itAddress.putExtra("merchant", details);
				startActivity(itAddress);
				break;
			case R.id.tv_phone:
				final String phone = details.getMobile();
				if (phone != null && !phone.isEmpty() && !phone.equals("无")) {
					HemaButtonDialog hbDialog = new HemaButtonDialog(mContext);
					hbDialog.setText("是否直接拨打"+phone+"?");
					hbDialog.setLeftButtonText("取消");
					hbDialog.setRightButtonText("拨打");
					hbDialog.setRightButtonTextColor(getResources().getColor(R.color.theme_orange));
					hbDialog.setButtonListener(new HemaButtonDialog.OnButtonListener() {

						@Override
						public void onLeftButtonClick(HemaButtonDialog dialog) {
							dialog.cancel();
						}

						@Override
						public void onRightButtonClick(HemaButtonDialog dialog) {
							dialog.cancel();
							Intent intent = new Intent(Intent.ACTION_CALL,Uri.parse(
									"tel:" + phone));
							startActivity(intent);
						}
					});
				}else {
					showTextDialog("对方没有提供有效的电话号码");
				}
				break;
			case R.id.tv_consult_online://咨询
				if (BaseUtil.isLogin()) {
					String mQQNum = details.getQq();
					if (isNull(mQQNum)) {
						XtomToastUtil.showShortToast(mContext, "对方没有指定QQ");
						break;
					}
					String url="mqqwpa://im/chat?chat_type=wpa&uin="+mQQNum;
					try {
						startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
					} catch (Exception e) {
						showTextDialog("打开QQ客户端失败\n请确保已经安装了QQ手机客户端");
						e.printStackTrace();
					}
				} else {
					Intent itLogin = new Intent(mContext, LoginActivity.class);
					startActivity(itLogin);
				}
				break;
            case R.id.layout_all_production:
                lineIntroduce.setVisibility(View.GONE);
                lineProducts.setVisibility(View.VISIBLE);
                layout_info.setVisibility(View.GONE);
                listview.setVisibility(View.VISIBLE);
                break;
            case R.id.layout_introduce:
                lineIntroduce.setVisibility(View.VISIBLE);
                lineProducts.setVisibility(View.GONE);
                layout_info.setVisibility(View.VISIBLE);
                listview.setVisibility(View.GONE);
                break;
			case R.id.iv_info:
                Intent itLarge2 = new Intent(mContext, ShowLargeImageActivity.class);
                String imgurl_detail2 = details.getImgurl0();
                ArrayList<Img> imgs2 = new ArrayList<Img>();
                Img img2 = new Img(imgurl_detail2);
                imgs2.add(img2);
                itLarge2.putExtra("imgs", imgs2);//所有的图片地址
                itLarge2.putExtra("position", 1);//当前是第几张图片
                startActivity(itLarge2);
				break;
		}
	}

}
